package cn.wolfcode.cms.shiro;

import cn.wolfcode.cms.domain.Employee;
import cn.wolfcode.cms.domain.Role;
import cn.wolfcode.cms.service.IEmployeeService;
import cn.wolfcode.cms.service.IPermissionService;
import cn.wolfcode.cms.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {


    @Setter
    private IEmployeeService employeeService;

    @Setter
    private IRoleService roleService;

    @Setter
    private IPermissionService permissionService;



    public String getName() {
        return "EmployeeRealm";
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取当前页面输入的账号
        String username  = (String) token.getPrincipal();

        //通过账号查询数据库
        Employee emp = employeeService.getEmployeeByName(username);

        //如果为null表示登录失败
        if(emp == null){
            return null;
        }
        //登录成功
        return  new SimpleAuthenticationInfo(emp, emp.getPassword(), getName());
    }





    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //当前登录用户
        Employee currentUser = (Employee) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        if(currentUser.isAdmin()){
            //超级管理员
            //拥有所有用户角色
            List<Role> roles = roleService.selectAll();
            for (Role r : roles) {
                info.addRole(r.getSn());
            }
            //拥有所有权限
            info.addStringPermission("*:*");
        }else{
            //普通用户
            //角色
            List<String> roles = roleService.getRoleSnByEmpId(currentUser.getId());
            info.addRoles(roles);

            //权限
            List<String> permissions = permissionService.getPermissionResourcesByEmpId(currentUser.getId());
            info.addStringPermissions(permissions);
        }
        return info;
    }

}
